const { Controller } = require('egg')
const createRule = {
	username: {
		type: 'string',
		required: true,
	},
	password: {
		type: 'string',
		required: true,
	},
}
const indexRule = {
	pageSize: 'string',
	pageNum: 'string',
}
/**
 * @controller user 用户
 */
class UserController extends Controller {
	/**
	 * @summary 用户列表
	 * @description 用户列表
	 * @router get /admin/users
	 * @request query number pageSize eg:10 页尺寸
	 * @request query number pageNum eg:1 页码
	 */
	async index() {
		const ctx = this.ctx
		try {
			ctx.validate(indexRule, ctx.request.query)
			const { count, rows } = await ctx.service.user.index(
				ctx.request.query
			)
			const data = {
				list: rows,
				total: count,
			}
			ctx.helper.success(data)
		} catch (e) {
			ctx.helper.error(e)
		}
	}

	/**
	 * @summary 创建用户
	 * @description 创建用户
	 * @router post /admin/users
	 * @request body createUserRequest
	 */
	async create() {
		const ctx = this.ctx
		try {
			ctx.validate(createRule, ctx.request.body)
			const status = await ctx.service.user.create(ctx.request.body)
			if (status === 'success') {
				ctx.helper.success('创建成功')
			} else {
				ctx.helper.error(status)
			}
		} catch (e) {
			ctx.helper.error(e)
		}
	}

	/**
	 * @summary 删除用户
	 * @description 删除用户
	 * @router delete /admin/users/{id}
	 * @request path string *id 标识
	 */
	async destroy() {
		const ctx = this.ctx
		try {
			const { id } = ctx.params
			const status = await ctx.service.user.destroy(id)
			if (status === 'success') {
				ctx.helper.success('删除成功')
			} else {
				ctx.helper.error(status)
			}
		} catch (e) {
			ctx.helper.error(e)
		}
	}

	/**
	 * @summary 更新用户
	 * @description 更新用户
	 * @router put /admin/users/{id}
	 * @request path string *id 标识
	 * @request body updateUserRequest
	 */
	async update() {
		const ctx = this.ctx
		try {
			const { id } = ctx.params
			const status = await ctx.service.user.update(id, ctx.request.body)
			if (status === 'success') {
				ctx.helper.success('更新成功')
			} else {
				ctx.helper.error(status)
			}
		} catch (e) {
			ctx.helper.error(e)
		}
	}
}

module.exports = UserController
